//
//  pullLayout.m
//  CollectionView_自定义布局
//
//  Created by dllo on 15/8/18.
//  Copyright (c) 2015年 zdh. All rights reserved.
//

#import "DailyPullLayout.h"
#import "ArticleModel.h"
#import "DailyHeader.h"

@interface DailyPullLayout () 

@property (nonatomic,assign) CGFloat offLeft;
@property (nonatomic,assign) CGFloat offRight;

@end

@implementation DailyPullLayout


- (void)dealloc
{
    [_dicArr release];
    [_arr release];
    [super dealloc];
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.arr = [NSMutableArray array];
        self.dicArr = [NSMutableArray array];
    }
    return self;
}
- (void)prepareLayout
{
    [super prepareLayout];
    [self.arr removeAllObjects];
    [self calculatHeighet];
}
- (void)calculatHeighet
{
    NSInteger RealWidth = [UIScreen mainScreen].bounds.size.width/2;
    
    NSInteger num = [self.collectionView numberOfItemsInSection:0];
    
    self.offLeft = 0 + 260+[UIScreen mainScreen].bounds.size.width/2;
    self.offRight = 0 + 260+[UIScreen mainScreen].bounds.size.width/2;
    
    for (int i = 0; i < num; i++) {
        NSIndexPath *index = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *atts = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:index];
        
        ArticleModel * model = [self.dicArr objectAtIndex:i];
        NSDictionary *dic = [model.simgs objectAtIndex:0];
        CGFloat width = [[dic objectForKey:@"width"] floatValue];
        CGFloat height = [[dic objectForKey:@"height"] floatValue];
        CGFloat realHeight = height * RealWidth / width;//同比率缩放
        
        if (i % 2 == 0) {
            atts.frame = CGRectMake(0, _offLeft + 5, RealWidth, realHeight);
            _offLeft += realHeight + 5;
        } else {
            atts.frame = CGRectMake(RealWidth + 5, _offRight + 5, RealWidth, realHeight);
            _offRight += realHeight + 5;
        }
        [self.arr addObject:atts];
    }
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *currentArr = [NSMutableArray array];
    for (UICollectionViewLayoutAttributes *att in self.arr) {
        if (CGRectIntersectsRect(att.frame, rect) || CGRectContainsRect(att.frame, rect)) {
            [currentArr addObject:att];
        }
    }
    return currentArr;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return [self.arr objectAtIndex:indexPath.item];
}
//设置滚动大小
- (CGSize)collectionViewContentSize
{
    CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width, _offLeft > _offRight ? _offLeft : _offRight);
    return size;
}
@end
